package com.topvision.myviewtest.algorithm.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.topvision.myviewtest.R;
import com.topvision.myviewtest.algorithm.util.SortTestHelper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SortActivity extends AppCompatActivity {
    private TextView mTvResult;
    private StringBuffer mStringBuffer = new StringBuffer();
    private long startTime;
    private long endTime;
    private Thread mSortThread;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sort);
        mTvResult = (TextView) findViewById(R.id.tv_result);
        int number = getIntent().getIntExtra(SortTestHelper.SORT_NAME_KEY, -1);
        mStringBuffer.append("方案 | ").append(SortTestHelper.getSortNameValue(number)).append("\n");
        mTvResult.setText("正在异步排序,耐心等待...");

        startSort();
    }

    /** 开始排序 */
    private void startSort() {
        mSortThread = new Thread(new SortRunnable());
        mSortThread.start();
    }

    /**
     * 排序线程
     */
    class SortRunnable implements Runnable {
        @Override
        public void run() {
            sort();
        }
    }

    /**
     * 反射调用函数，实现Activity不需要管理
     */
    private Integer[] getClassArray(Class clazz) {
        try {
            startTime = System.nanoTime();
            Class<?> sortClass = Class.forName(clazz.getName());
            Method method = sortClass.getMethod(SortTestHelper.METHOD_SORT);
            Integer[] integers = (Integer[]) method.invoke(null);
            endTime = System.nanoTime();
            return integers;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 开始排序，并记录排序耗时情况
     */
    private void sort() {
        Class clazz = (Class) getIntent().getSerializableExtra(SortTestHelper.SORT_CLASS_KEY);
        Integer[] arr = getClassArray(clazz);
        if (checkResult(arr)) {
            mStringBuffer
                    .append("长度 | ")
                    .append(arr.length)
                    .append("\n耗时 | ")
                    .append((endTime - startTime) / 1000_000_000f)
                    .append("秒");
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvResult.setText(mStringBuffer.toString());
            }
        });
    }

    /**
     * 默认排序规则为从小到大，检验排序后结果准确性
     *
     * @param arr 需要检验的数组
     * @return 准确性
     */
    private boolean checkResult(Integer[] arr) {
        if (arr == null || arr.length == 0) {
            return false;
        }
        int length = arr.length;
        for (int i = 0; i < length; i++) {
            if (i < length - 1 && arr[i] > arr[i + 1]) {
                mStringBuffer.append("排序结果错误!");
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSortThread.interrupt();
    }
}
